/**
 * JAVACC DEMO 1.0
 */

package com.apache.rpc.common;

import com.apache.api.vo.ResultEntity;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.*;

/**
 * description:  获取配置信息工具类
 *
 * @author ius 创建时间：2016-7-23
 */
public class RpcUtil {

    private static transient Map<String, Long> countMap = new HashMap<String, Long>(1);

    private static RpcUtil instance;

    private static transient String version = "";

    private RpcUtil() {
        filePath = ConfigUtil.getClassLoaderPath() + "config/";
    }

    public static RpcUtil getInstance() {
        if (null == instance) {
            instance = new RpcUtil();
        }
        return instance;
    }

    public static String getVersion() {
        return version;
    }

    public void setVersion(String rpcVersion) {
        if (StrUtil.isNotNull(rpcVersion)) {
            this.version = rpcVersion;
        }
    }

    /**
     * 判断对象是否为空
     *
     * @param obj 传入的对象
     * @return 如果obj为空返回true，不为空返回false
     */
    public static boolean isEmpty(Object obj) {
        return obj == null;
    }

    /**
     * 判断一个list集合是否为空
     *
     * @param list 传入的list
     * @return 如果list为空或者长度为0返回true，不为空返回false
     */
    public static boolean isEmpty(List list) { //
        return list == null || list.size() == 0;
    }

    /**
     * 判断一个list集合是否为空
     *
     * @param collection 传入的集合
     * @return 如果collection为空或者长度为0返回true，不为空返回false
     */
    public static boolean isEmpty(Collection collection) { //
        return collection == null || collection.isEmpty();
    }

    public long getCountMap(String key) {
        if (null == countMap.get(key))
            return 0;
        return countMap.get(key);
    }

    public void setCountMap(String key) {
        synchronized (countMap) {
            countMap.put(key, (countMap.get(key) + 1));
        }
    }

    public void delCountMap(String key) {
        synchronized (countMap) {
            if (null != countMap.get(key))
                countMap.put(key, (countMap.get(key) - 1));
        }
    }

    private Long lastUpateTime = 0l;//最后修改时间

    private Map<String, String> constant = new HashMap<String, String>(1);//存放系统配置参数

    private String filePath = "";

    /**
     * description: 加载配置文件
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    private String initConfig(String key) {
        Properties prop = null;
        String fileName = "rpc_config.properties";
        if (filePath.indexOf(".jar") != -1) {
            if (isEmpty(constant.get(fileName))) {
                prop = ConfigUtil.getInstance().getProperties(filePath, fileName);
            }
        } else {
            File oldfile = new File(filePath + fileName);
            if (oldfile.exists()) {
                long lastModletime = oldfile.lastModified();
                if (lastModletime > lastUpateTime) {//有更新从新加载
                    lastUpateTime = lastModletime;
                    prop = ConfigUtil.getInstance().getProperties(filePath + fileName);
                }
            }
        }
        if (null != prop) {
            Map<String, String> map = new HashMap<String, String>((Map) prop);
            Set propertySet = map.entrySet();
            for (Object o : propertySet) {
                Map.Entry entry = (Map.Entry) o;
                constant.put(entry.getKey().toString(), entry.getValue().toString());
            }
        }
        if (ConfigUtil.isNull(key)) {
            return "";
        } else {
            return ConfigUtil.isNull(constant.get(key), "");
        }
    }

    /**
     * 获取property文件的属性值
     *
     * @param key
     * @return
     */
    public String getValueByKey(String key) {
        String result = initConfig(key);
        return result;
    }

    /**
     * 获取某个配置文件下的所有配置信息
     *
     * @return
     */
    public Map<String, String> getAllProperty() {
        return constant;
    }

    /**
     * 判断socket是否通
     */
    public boolean isHostConnectable(String host, String port) {
        Socket socket = null;
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(host, Integer.parseInt(port)), 100);
        } catch (IOException e) {
            return false;
        } finally {
            IOUtils.closeQuietly(socket);
        }
        return true;
    }

    public static void main(String args[]) {
        //        String str = "usage_patterns=0\n" + "#信息删除状态\n" + "INFO_DEL_STATUS=-1\n" + "#系统名称\n"
        //                + "sys_ename=rpc-server\n" + "#RPC系统超级用户(只能是一个,默认为admin)\n"
        //                + "console.user=admin\n";
        //        InputStream stream = null;
        //        try {
        //            stream = IOUtils.toInputStream(str);
        //            Properties prop = new Properties();
        //            prop.load(stream);
        //            Map<String, String> map = new HashMap<String, String>((Map) prop);
        //            System.out.println(map);
        //        } catch (Exception e) {
        //        } finally {
        //            IOUtils.closeQuietly(stream);
        //        }
        Socket socket = null;
        try {
            String xmlParams =
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<xml-body>\n" + "    <Head>\n"
                            + "        <Version>1.0</Version>\n"
                            + "        <MethodCode>protocolAction</MethodCode>\n"
                            + "        <BeanId>rpcService</BeanId>\n"
                            + "        <ParamType>json</ParamType>\n"
                            + "        <SocketClose>false</SocketClose>\n"
                            + "        <ProtocolType>socket</ProtocolType>\n" + "    </Head>\n"
                            + "    <Body>\n" + "        <id>0</id>\n"
                            + "        <Client-IP>127.0.0.1</Client-IP>\n"
                            + "        <nowSysUser>1</nowSysUser>\n"
                            + "        <ifIus>true</ifIus>\n" + "        <method>list</method>\n"
                            + "        <iusId>8ca1663cc6844f41bf94f7ed87fc7aec</iusId>\n"
                            + "        <nowOrgId>4f5213b3dcb740c8abfd9bd5a86368c4</nowOrgId>\n"
                            + "        <sysPass>iussoft2018</sysPass>\n" + "    </Body>\n"
                            + "</xml-body>";
            //System.out.println(xmlParams);
            socket = new Socket();
            //设置socket发包缓冲为32k；
            //socket.setSendBufferSize(32 * 1024);
            socket.setReceiveBufferSize(32 * 1024);
            SocketAddress remoteAddr = new InetSocketAddress("111.198.38.220",
                    Integer.parseInt("4001"));
            //            SocketAddress remoteAddr = new InetSocketAddress("127.0.0.1", Integer.parseInt("4003"));
            socket.connect(remoteAddr, 30000); //等待建立连接的超时时间为30秒
            socket.setSoTimeout(Integer.parseInt(
                    StrUtil.doNull(ConfigUtil.getInstance().getValueByKey("socketTimeOut"),
                            "200000")));//毫秒
            String temp = "";
            // 将输出流包装为打印流
            PrintWriter printWriter = new PrintWriter(
                    new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
            printWriter.write(xmlParams);
            printWriter.flush();
            // 关闭输出流
            socket.shutdownOutput();

            StringBuilder rtnMsgc = new StringBuilder();

            byte[] bs_Length = new byte[4];
            int readLength = socket.getInputStream().read(bs_Length, 0, 4);
            int dataLength = bs_Length[0] & 0xFF;
            // "|="按位或赋值。
            dataLength |= ((bs_Length[1] << 8) & 0xFF00);
            dataLength |= ((bs_Length[2] << 16) & 0xFF0000);
            dataLength |= ((bs_Length[3] << 24) & 0xFF000000);
            System.out.println(dataLength);
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), "UTF-8"));
            String str;
            while ((str = rd.readLine()) != null) {
                rtnMsgc.append(str + "\n");
            }
            //        temp = IOUtils.toString(socket.getInputStream(), "UTF-8");
            temp = rtnMsgc.toString();
            printWriter.close();
            System.out.println(temp);
            //            JSONObject json = JSONObject.fromObject(temp);
            //            Object sst = json.get("entity");
            //            if (sst instanceof JSONArray) {
            //                System.out.println(sst);
            //            }
            //            ResultEntity resultEntity = new ResultEntity();
            //            resultEntity.setResult(json.getString("result"));
            //            resultEntity.setMessage(json.getString("message"));
            //            resultEntity.setEntity(json.get("entity"));
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                ResultEntity studentList = objectMapper.readValue(temp, ResultEntity.class);
                System.out.println(studentList);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //            ResultEntity entity = JsonEntityParese.instance()
            //                    .jsonToJavaBean(temp, ResultEntity.class, Map.class);
            byte[] dataByteArr = temp.getBytes("UTF-8");
            int dataLen = dataByteArr.length;
            System.out.println(dataLen);
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
            }
            //IOUtils.closeQuietly(server);
        }
    }
}
